<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"/>
    <title>主页</title>
    <script src="jquery.min.js"></script>

    <script type="text/javascript">

        var ws ;

        function connect(){
            ws = new WebSocket("ws://"+window.location.host+"/websocket?user_name="+$("#user-name").val());
            // 连接成功建立的回调方法
            ws.onopen = function()
            {
            	console.log("连接成功");
            };
            //接收到消息的回调方法 
            ws.onmessage = function(evt)
            {
                var data = JSON.parse(evt.data);
                $("#receiveMsg").val($("#receiveMsg").val()+ "接收消息------>"+data.sender+"--->:"+data.message+"\r\n");
            };
            //关闭连接回调
            ws.onclose = function(evt) { console.log("WebSocketClosed!"); };
			//消息出错回调
            ws.onerror = function(event) {  
                alert(event);  
            };  
        }

        function send() {
            var object = new Object();
            object.sender = $("#user-name").val();
            object.receiver = $("#receiver").val();
            object.receiver1 = $("#receiver1").val();
            object.message = $("#message").val();
            ws.send(JSON.stringify(object));
            $("#receiveMsg").val($("#receiveMsg").val()+ "发送消息------>"+ $("#receiver").val()+"--->:"+$("#message").val()+"\r\n");
            $("#receiveMsg").val($("#receiveMsg").val()+ "发送消息------>"+ $("#receiver1").val()+"--->:"+$("#message").val()+"\r\n");
        }
        //关闭连接  
        function closeWebSocket() {  
            ws.close();  
        }  

    </script>
</head>
<body>
<h1>Welcome Body!</h1>
用户名:<input type="text" id="user-name"/> <input type="button" value="连接" onclick="connect()"/> 
<input type="button" value="关闭连接" onclick="closeWebSocket()"/>
<br/>
发送消息:<br/>
接受者1:<input type="text" id="receiver" /><br/>
接受者2:<input type="text" id="receiver1" /><br/>
消息:<input type="text" id="message"/><br/>
<input type="button" value="发送" onclick="send()"/>
<br/>
<br/>
接受消息:<br/>
<textarea id="receiveMsg" style="height: 250px;width: 800px;" readonly="true"></textarea>

</body>
</html>